package com.lengxf.milo;

import com.lengxf.milo.executor.ReadExecutor;
import com.lengxf.milo.executor.SubscriptionExecutor;
import com.lengxf.milo.executor.WriteExecutor;
import com.lengxf.milo.model.ReadResult;
import com.lengxf.milo.model.WriteParam;
import com.lengxf.milo.model.WriteResult;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.stack.core.UaException;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

public class OpCuaClientTest {


    private static UaClient uaClient;

    private static final List<String> nodeIdList = List.of("ns=3;i=1001", "ns=3;i=1002", "ns=3;i=1004");

    static {
        try {
            uaClient = OpcUaClient.create("opc.tcp://Mac:53530/OPCUA/SimulationServer").connect().get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws UaException, ExecutionException, InterruptedException {
        readTest();
//        writeTest();
        readTest();
        subscriptionTest();
        new CountDownLatch(1).await();
    }

    public static void readTest() throws UaException, ExecutionException, InterruptedException {
        System.out.println("ReadStart--------------------------------------------");

        List<ReadResult> result = ReadExecutor.read(uaClient, nodeIdList);
        result.forEach(System.out::println);

        System.out.println("ReadEnd--------------------------------------------");
    }

    public static void writeTest() throws UaException, ExecutionException, InterruptedException {
        System.out.println("WriteStart--------------------------------------------");

        List<WriteParam> list = List.of(
                new WriteParam("ns=3;i=1001", true),
                new WriteParam("ns=3;i=1002", 2.1f),
                new WriteParam("ns=3;i=1004", "字符串1")
        );
        List<WriteResult> resultList = WriteExecutor.write(uaClient, list);
        resultList.forEach(System.out::println);

        System.out.println("WriteEnd--------------------------------------------");
    }

    public static void subscriptionTest() throws UaException, ExecutionException, InterruptedException {
        System.out.println("subscriptionTestStart--------------------------------------------");

        SubscriptionExecutor.subscribe(uaClient, nodeIdList);

        System.out.println("subscriptionTestEnd--------------------------------------------");
    }


}
